package com.xl.basic.utils;

import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import com.xl.basic.entity.ResultException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.Set;

import static jakarta.validation.Validation.buildDefaultValidatorFactory;

/**
 * validator验证器
 * 尽量使用注解@Validated
 */

public class ValidatorUtils {
    private static Validator validator;

    public static <T, S> Result<S> validate(T param) {
        if (validator == null) {
            try (ValidatorFactory validatorFactory = buildDefaultValidatorFactory()) {
                validator = validatorFactory.getValidator();
            } catch (Exception e) {
                return ResultEnums.Exception.getResult(e.toString());
            }
        }

        Set<ConstraintViolation<T>> constraintViolations = validator.validate(param);
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            return ResultEnums.ParamError.getResult(constraintViolation.getMessage());
        }

        return ResultEnums.Success.getResult();
    }

    public static <T> void validateThrowError(T param) {
        if (validator == null) {
            try (ValidatorFactory validatorFactory = buildDefaultValidatorFactory()) {
                validator = validatorFactory.getValidator();
            } catch (Exception e) {
                throw new ResultException(ResultEnums.Exception.getResult(e.toString()));
            }
        }

        Set<ConstraintViolation<T>> constraintViolations = validator.validate(param);
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            throw new ResultException(ResultEnums.ParamError.getResult(constraintViolation.getMessage()));
        }
    }
}
